package com.venutech.gongan.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.utils.PageUtils;
import com.venutech.gongan.common.BusinessException;
import com.venutech.gongan.dao.QRCodeMapper;
import com.venutech.gongan.entity.DictData;
import com.venutech.gongan.entity.QRCode;
import com.venutech.gongan.service.DictDataService;
import com.venutech.gongan.service.QRCodeService;
import com.venutech.gongan.util.DateUtils;
import com.venutech.gongan.util.MD5Util;
import com.venutech.gongan.util.QRCodeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;


@Service
public class QRCodeServiceImpl implements QRCodeService {

    Logger logger = LoggerFactory.getLogger(QRCodeServiceImpl.class);

    @Value("${qrcode.external-domain}")
    String qrCodeExternalDomain;

    @Value("${qrcode.save-dir}")
    String qrCodeSaveDir;

    @Value("${qrcode.path-mapping}")
    String qrCodePathMapping;

    @Autowired
    private ResourceLoader resourceLoader;

    @Resource
    private QRCodeMapper qrCodeMapper;

    @Resource
    private DictDataService dictDataService;


    @Override
    public int createQrCodeWithFile(String xh,String qybm,String xlxbm) throws IOException {
        QRCode qrCode = new QRCode();
        qrCode.setXh(xh);
        qrCode.setQybm(qybm);
        qrCode.setXlxbm(xlxbm);
        insert(qrCode);
        int qr_id = qrCode.getQr_id();

        String qrIdMD5 = MD5Util.MD5Encode(String.valueOf(qr_id), "UTF-8");
        String codeContent=String.format("%s?qr_id=%s", qrCodeExternalDomain, qrIdMD5);    //二维码APP入口地址
        String fileName = qr_id +".png";
        QRCode newQrCode = getById(qr_id);
        newQrCode.setQr_codeContent(codeContent);
        newQrCode.setQrid_md5(qrIdMD5);
        newQrCode.setQr_codeImgFileSaveDir(fileName);   // 此处只保存文件名称，不带路径，路径配置化
        updateQRCode(newQrCode);

        logger.info("二维码codeContent："+codeContent);
        //二维码物理保存地址
        File codeImgFileSaveDir = new File(qrCodeSaveDir);
        org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:static/qrcodebg.png");
        if(!resource.exists()) {
            throw new BusinessException(String.format("gbImgfile not exists [%s]", resource.getURL()));
        }
        int length = (int)resource.contentLength();
        byte[] fileData = new byte[length];
        resource.getInputStream().read(fileData);
        // 调用工具类生成二维码并输出到输出流中
        // QRCodeUtil.createCodeToFile(codeContent,codeImgFileSaveDir,fileName,fileData,120,250);
        QRCodeUtil.createCodeToFile(codeContent,codeImgFileSaveDir,fileName);   // 根据批量生产二维码的要求，不需要生成带背景的图片
        return qr_id;
    }

    @Override
    public int insert(QRCode qrCode) {
        return qrCodeMapper.insert(qrCode);
    }

    @Override
    public Integer getLastSeq() {
        return qrCodeMapper.getLastSeq();
    }

    @Override
    public int getEightSeq() {
        return qrCodeMapper.getEightSeq();
    }

    @Override
    public int updateQRCode(QRCode qrCode) {
        return qrCodeMapper.updateQRCode(qrCode);
    }

    @Override
    public QRCode getById(Integer qr_id) {
        return qrCodeMapper.getById(qr_id);
    }

    @Override
    public int deleteById(Integer qr_id) {
        return qrCodeMapper.deleteById(qr_id);
    }

    @Override
    public List<QRCode> getQrBm() {
        return qrCodeMapper.getQrBm();
    }

    @Override
    public QRCode getByQrbm(String qr_bm) {
        return qrCodeMapper.getByQrbm(qr_bm);
    }


    @Override
    public Page<QRCode> getInfo(Integer pageNo, Integer pageSize, String begintime, String endtime, String badw, String qr_id) {
        Page<QRCode> page = new Page<>(pageNo,pageSize);
        PageUtils.startPage();
        List<QRCode> list = qrCodeMapper.getInfo(begintime,endtime,badw,page,qr_id);
        page.setTotal(new PageInfo<>(list).getTotal());
        //区域编码
        List<DictData> list_dict = dictDataService.getSelQybm();
        List<DictData> listxlbm = dictDataService.getSelXlbm();
        for (DictData data:list_dict) {
            for(QRCode qrCode:list){
                if (!data.getDict_label().equals("姑苏区")){
                    if(data.getDict_value().equals(qrCode.getQybm())){
                        qrCode.setQybm(data.getDict_label());
                    }
                }
            }
        }

        for(DictData data:listxlbm){
            for(QRCode qrCode:list){
                if (!data.getDict_label().equals("姑苏区")){
                    if(data.getDict_value().equals(qrCode.getXlxbm())){
                        qrCode.setXlxbm(data.getDict_label());
                    }
                }
            }
        }

        for(QRCode qrCode:list){
            if (qrCode.getCreate_time()!= null) {
                qrCode.setCreate_time_str(DateUtils.dateToStr(qrCode.getCreate_time()));
            }
        }

        return page.setRecords(list);
    }


    @Override
    public QRCode getByIdMD5(String qrIdMD5) {
        return qrCodeMapper.getByIdMD5(qrIdMD5);
    }

    @Override
    public QRCode getByQrBm(String qr_bm) {
        return qrCodeMapper.getByQrbm(qr_bm);
    }

    @Override
    public List<String> getBindedQrIdMd5List(int num) {
        return qrCodeMapper.getBindedQrIdMd5ListOrderByMd5(num);
    }
}
